#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
import logging


class ToneLogger(object):
    LEVELS = {
        'DEBUG': logging.DEBUG,
        'INFO': logging.INFO,
        'WARN': logging.WARNING,
        'ERROR': logging.ERROR,
        'CRITICAL': logging.CRITICAL
    }

    def __init__(self, name='', level='INFO', propagate=False):
        """Tone logger

        :param name: log name
        :param level: log level
        :param propagate:
        """
        self.level = level if not os.environ.get("TONE_DEBUG") else 'DEBUG'
        self.propagate = propagate
        if not name:
            self.name = str(os.getpid())
        else:
            self.name = name

        self.logger = logging.getLogger(self.name)
        self.logger.setLevel(self.LEVELS.get(self.level))
        self.logger.propagate = self.propagate

    def add_handler(self, handler):
        """Add Log Handler"""
        self.logger.addHandler(handler.handler)
        if isinstance(handler, ToneFileHandler):
            print('ToneLogger file: {}'.format(handler.filename))
        return self

    def debug(self, msg):
        self.logger.debug(msg)

    def info(self, msg):
        self.logger.info(msg)

    def warning(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)

    def critical(self, msg):
        self.logger.critical(msg)


class LoggerHandler(object):
    def __init__(self):
        self.handler = None
        self.formatter = logging.Formatter(
            '%(asctime)s <%(name)s> [%(levelname)s]: %(message)s',
            '%b %d %H:%M:%S'
        )


class ToneFileHandler(LoggerHandler):
    def __init__(self, filename='', mode='w'):
        """Tone File Log Handler

        :param filename: file name
        :param mode: log mode
        """
        super(ToneFileHandler, self).__init__()
        self.mode = mode
        if filename:
            self.filename = filename
        else:
            self.filename = "tone_{}_{}.log".format(os.getpid(), int(time.time()))
        self.logfile = os.path.join(
            os.path.realpath("."),
            self.filename)

        self.handler = logging.FileHandler(
            self.logfile,
            mode=self.mode,
            encoding='UTF-8',
            delay=False
        )
        self.handler.setFormatter(self.formatter)


class ToneStreamHandler(LoggerHandler):
    def __init__(self):
        """Tone Stream Log Handler"""
        super(ToneStreamHandler, self).__init__()
        self.handler = logging.StreamHandler()
        self.handler.setFormatter(self.formatter)


logger = ToneLogger(name="tone").add_handler(ToneStreamHandler())
